from PyQt5.QtWidgets import QFrame, QLabel
from PyQt5.QtCore import QRect, QTimer, Qt


class PercentBar(QFrame):
    def __init__(self, parent, size=100, font=20, color='green', percent=0):
        super().__init__(parent)
        self.percent = percent
        self.font = font
        self.color = color
        self.setFrameShape(QFrame.StyledPanel)
        # 设置无边框和背景透明paintEvent
        self.setWindowFlags(Qt.FramelessWindowHint)

        self.setMinimumWidth(size)
        self.setMinimumHeight(size)
        self.setMaximumWidth(size)
        self.setMaximumHeight(size)

        self.line = int(self.width()/7)
        self.text_size = self.width()-self.line*2
        self.text_radius = int((self.text_size-1)/2)
        self.bar_radius = int((self.width()-1)/2)

        self.text = QLabel(self)
        self.text.setGeometry(QRect(self.line, self.line, self.text_size, self.text_size))
        self.text.setStyleSheet(f"border-radius:{self.text_radius}px; background-color: #F4F4F4; font-size:{self.font}px;")
        self.text.setText("0%")
        self.text.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)

        self.timer = QTimer()
        # 定时器触发修改Stlye
        self.timer.timeout.connect(self.progress)
        # 定时器触发时间粒度
        self.timer.start(10)
        self.timers = 0

    def progress(self):
        def progressBar_change(value):
            index2 = str(float(100 - value) / 100 - 0.001)
            index = str(float(100 - value) / 100)
            style = f"border-radius:{self.bar_radius}px; background-color: qconicalgradient(cx:0.5, cy:0.5, angle:90, stop:index #00ffffff, stop:index2 {self.color});"
            newstyle = style.replace("index", index).replace("index2", index2)
            self.setStyleSheet(newstyle)
        self.timers = self.timers + 1
        if self.timers > self.percent:
            self.timer.stop()
        else:
            progressBar_change(self.timers)
            self.text.setText(str(self.percent) + "%")
